package com.alon.spring01.study.threadLocal;

import java.lang.ref.WeakReference;

/**
 * @program: spring01
 * @description: 测试ThreadLocal, 达到线程隔离机制，确保线程安全
 * @author: yulongguang
 * @create: 2019-07-16 22:19
 **/
public class SeqCount2 {

    /**
     * 返回对象
     */

    private static ThreadLocal<A> threadLocal = new ThreadLocal<A>() {
        @Override
        public A initialValue() {
            A a = new A();
            return a;
        }
    };

    private static class SeqThread extends Thread {
        private SeqCount2 seqCount;

        SeqThread(SeqCount2 seqCount) {
            this.seqCount = seqCount;
        }

        @Override
        public void run() {
            for (int i = 0; i < 3; i++) {
                threadLocal.get().setNumber(threadLocal.get().getNumber() + 5);
                System.out.println(Thread.currentThread().getName() + "seqCount:" + threadLocal.get().getNumber());
            }
        }
    }

    public static void main(String[] args) {
        SeqCount2 seqCount = new SeqCount2();
        SeqThread seqThread1 = new SeqThread(seqCount);
        SeqThread seqThread2 = new SeqThread(seqCount);
        SeqThread seqThread3 = new SeqThread(seqCount);
        SeqThread seqThread4 = new SeqThread(seqCount);
        seqThread1.start();
        seqThread2.start();
        seqThread3.start();
        seqThread4.start();

    }

    static class A {
        private int number = 0;

        public int getNumber() {
            return number;
        }

        public void setNumber(int number) {
            this.number = number;
        }
    }

}
